/*
 * Copyright (C) 2009, 2010 M. Homs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.homs.jsunit.runner;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.homs.jsunit.exception.JavascriptException;

public class Jdk6Runner implements Runner {

	private static final String[] ENGINE_NAMES = new String[] { //
	"js", "rhino", "JavaScript", "javascript", "ECMAScript", "ecmascript"//
	};

	protected ScriptEngine engine;

	public Jdk6Runner() {
		super();
		final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
		ScriptEngine e;

		for (final String engineAlias : ENGINE_NAMES) {
			e = scriptEngineManager.getEngineByName(engineAlias);
			if (e != null) {
				this.engine = e;
				break;
			}
		}
		if (this.engine == null) {
			throw new JavascriptException("JavaScript/ECMAScript/Rhino engine not found");
		}
	}

	public Object evalScript(final String scriptName) {
		BufferedReader br;
		try {
			final InputStream url = Thread.currentThread().getContextClassLoader().getResourceAsStream(
					scriptName);
			br = new BufferedReader(new InputStreamReader(url));
		} catch (final Exception e) {
			throw new JavascriptException("error opening script: " + scriptName, e);
		}
		try {
			return engine.eval(br);
		} catch (final ScriptException e) {
			throw new JavascriptException("error evaluating script: " + scriptName, e);
		}
	}

	public Object eval(final String expression) {
		try {
			return engine.eval(expression);
		} catch (final ScriptException e) {
			throw new JavascriptException("error evaluating: " + expression, e);
		}
	}

	public ScriptEngine getEngine() {
		return engine;
	}

	public void close() {
	}

	public Object get(final String varName) {
		return engine.get(varName);
	}

	public Runner put(final String varName, final Object value) {
		engine.put(varName, value);
		return this;
	}
}
